
//
//  AmazingViewController.m
//  Only Love
//
//  Created by xalo on 16/5/6.
//  Copyright © 2016年 海城. All rights reserved.
//

#import "AmazingViewController.h"
#import "GetFilePath.h"
#import <AVFoundation/AVFoundation.h>
#import <AVKit/AVKit.h>
#import "UITableView+EmptyData.h"
#import "AmazeCell.h"
#import "PlayVideoController.h"
#import "GetFilePath.h"
@interface AmazingViewController ()<UINavigationControllerDelegate,UIImagePickerControllerDelegate,UITableViewDelegate,UITableViewDataSource>

@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (strong,nonatomic)NSMutableArray *dataSourceArray;//存放本地视频的地址
@property (strong,nonatomic)NSIndexPath *indexPath;
@end

@implementation AmazingViewController
#pragma mark  视图的生命周期
- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.navigationItem.title = @"惊喜的瞬间";
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    //添加右侧按钮，上传精彩视频
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"上传视频" style:UIBarButtonItemStylePlain target:self action:@selector(uploadVideo:)];
    
    //注册单元格
    [self.tableView registerNib:[UINib nibWithNibName:@"AmazeCell" bundle:nil] forCellReuseIdentifier:@"AmazeCell"];
    
    
}

- (void)viewWillAppear:(BOOL)animated{
    
    //从本地读取数据
    self.dataSourceArray = [self readArray];
    [self.tableView reloadData];
}
//上传视频按钮的回调方法
- (void)uploadVideo:(UIBarButtonItem *)sender{
    
    //调用上传视频的方法
    [self addVideo];
    
}
#pragma mark  添加录像
//添加录像
- (void)addVideo{
    
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    picker.delegate = self;
    picker.allowsEditing = YES;
    
    //判断是否为相机
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        
        picker.sourceType = UIImagePickerControllerSourceTypeCamera;
        picker.mediaTypes = [UIImagePickerController availableMediaTypesForSourceType:UIImagePickerControllerSourceTypeCamera];
        //设置录像质量
        picker.videoQuality = UIImagePickerControllerQualityTypeHigh;
        //设置录像最长时间
        picker.videoMaximumDuration = 600.0;
        picker.mediaTypes = [NSArray arrayWithObjects:@"public.movie", nil];
    }else{
        
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"本相机不支持录像功能" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alertView show];
    }
    [self presentViewController:picker animated:YES completion:nil];
    
}
#pragma mark   UIImagePickerViewController的代理方法
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    
    //获取到mediaTypes
    NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];
    BOOL success;
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if ([mediaType isEqualToString:@"public.movie"]) {
        
        NSString *videoPath = [GetFilePath getSavePathWithFileSuffix:@"mov"];
        success = [fileManager fileExistsAtPath:videoPath];
        if (success) {
            
            [fileManager removeItemAtPath:videoPath error:nil];
        }
        
        NSURL *videoURL = [info objectForKey:UIImagePickerControllerMediaURL];
        NSData *videoData = [NSData dataWithContentsOfURL:videoURL];
        [videoData writeToFile:videoPath atomically:YES]; //写入本地
        
        //存储数据
        success = [fileManager fileExistsAtPath:videoPath];
        if (success) {
            
            //存储成功将数据存入数组
            NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:videoPath,@"videoPath", nil];
            //从本地读取数据
            self.dataSourceArray = [self readArray];
            [self.dataSourceArray addObject:dic];
            //将数组写入本地
            [self writeToWithMemory:self.dataSourceArray];
            [self.tableView reloadData];
            NSLog(@"media 写入成功,video路径:%@",videoPath);
        }
    }
    [self dismissViewControllerAnimated:YES completion:nil];
    
}

#pragma mark ------tableView中dataSource相关的代理方法
//返回行高的代理方法
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return [tableView disPlayMessage:@"还没有视频哦，赶紧上传精彩的视频吧" withArrayCount:self.dataSourceArray.count];

}
//注册单元格
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    self.indexPath = indexPath;
    AmazeCell *cell = [tableView dequeueReusableCellWithIdentifier:@"AmazeCell" forIndexPath:indexPath];
    NSDictionary *dic = self.dataSourceArray[indexPath.row];
    NSString *fileStr = dic[@"videoPath"];
    //添加轻扫手势，删除视频
    UISwipeGestureRecognizer *swipe = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(deleteImage:)];
    swipe.direction = UISwipeGestureRecognizerDirectionLeft | UISwipeGestureRecognizerDirectionRight;
    [cell addGestureRecognizer:swipe];
    
    //将视频的第一帧转换为图片
    UIImage *image = [GetFilePath getImage:fileStr];
    cell.placeHolderImage.image = image;
    return cell;
}
#pragma mark  tableView中关于delegate相关的代理方法
//返回行高的代理方法
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return 200;
}
//点击单元格的代理方法
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    self.hidesBottomBarWhenPushed = YES;
    PlayVideoController *amzeingVC = [[PlayVideoController alloc] init];
    amzeingVC.receiveArray = self.dataSourceArray;
    amzeingVC.indexPath = indexPath;
    [self.navigationController pushViewController:amzeingVC animated:YES];
    self.hidesBottomBarWhenPushed = NO;
    
}
#pragma mark  编辑相关的代理方法
//允许编辑的回调方法
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return YES;
}

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return UITableViewCellEditingStyleDelete;
}
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        
        [self.dataSourceArray removeObjectAtIndex:indexPath.row];
        [self.tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
        //将删除后数组中的元素写入本地
        [self writeToWithMemory:self.dataSourceArray];
        [self.tableView reloadData];
    }
    
}
#pragma mark 数据存储相关的方法
//数组写入
- (void)writeToWithMemory:(NSMutableArray *)array {
    
    NSString *path = [[SandBoxPaths documentsPath] stringByAppendingPathComponent:@"Video.plist"];
    BOOL isWrite = [array writeToFile:path atomically:YES];
    if (!isWrite) {
        
        [self alertController:@"保存失败啦!快检查一下你的网络..."];
    }
}

//数组读取
- (NSMutableArray *)readArray {
    
    NSString *path = [[SandBoxPaths documentsPath] stringByAppendingPathComponent:@"Video.plist"];
    NSMutableArray *array = [[NSMutableArray alloc] initWithContentsOfFile:path];
    return array;
}
//弹出框
- (void)alertController:(NSString *)alertContent{
    
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"友情提示" message:alertContent preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *sureAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:nil];
    [alertController addAction:sureAction];
    [self presentViewController:alertController animated:YES completion:nil];
}
#pragma mark 属性的懒加载
-(NSMutableArray *)dataSourceArray{
    
    if (!_dataSourceArray) {
        
        _dataSourceArray = [NSMutableArray array];
    }
    return _dataSourceArray;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
